<template>
  <div class="container">
    <el-card class="box">
      <el-form :model="form" label-width="100px">
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="是否发布">
          <el-switch v-model="form.isPublished" />
        </el-form-item>
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit">确认</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { IssueAPI } from "@/api/api";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

const form = reactive({
  title: "",
  content: "",
  isPublished: true,
});

const handleSubmit = () => {
  IssueAPI(form.title, form.content, form.isPublished)
    .then(() => {
      ElMessage({
        showClose: true,
        message: "发布成功",
        type: "success",
      });
      resetForm();
      router.push("/");
    })
    .catch(error => {
      ElMessage({
        showClose: true,
        message: `发布失败: ${error.message || '未知错误'}`,
        type: "error",
      });
      console.error("发布失败", error);
    });
};

const handleCancel = () => {
  resetForm();
};

const resetForm = () => {
  form.title = "";
  form.content = "";
  form.isPublished = false;
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.box {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-button {
  min-width: 80px;
}
</style>
